package com.example.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.example.common.Result;
import com.example.entity.GreenHouse;
import com.example.entity.SensorData;
import com.example.entity.Sensors;
import com.example.mapper.GreenHouseMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GreenHouseService {

    @Resource
    private SensorService sensorService;
    @Resource
    private SensorDataService sensorDataService;
    @Resource
    private GreenHouseMapper greenHouseMapper;
    public Result listGreenHouse(GreenHouse greenHouse) {
        List<GreenHouse> greenHouseList = new ArrayList<>();
        if(greenHouse.getCode() != null){
            GreenHouse greenHouseByCode = greenHouseMapper.getGreenHouseBycode(greenHouse.getCode());
            greenHouseList.add(greenHouseByCode);
        } else if (greenHouse.getId() != null) {
            GreenHouse greenHouseById = greenHouseMapper.getGreenHouseById(greenHouse);
            greenHouseList.add(greenHouseById);
        }else {
            greenHouseList = greenHouseMapper.getGreenHouseList();
        }
        return Result.success(greenHouseList);
    }

    public Result addGreenHouse(GreenHouse greenHouse) {
        String code =  UUID.randomUUID().toString().replace("-", "").substring(0, 24);
        while(greenHouseMapper.getGreenHouseBycode(code) != null){
            code =  UUID.randomUUID().toString().replace("-", "").substring(0, 24);
        }
        Date date = DateUtil.date();
        greenHouse.setCreatedAt(date);
        greenHouse.setUpdatedAt(date);
        greenHouse.setCode(code);
        greenHouseMapper.createGreenHouse(greenHouse);
        return Result.success("添加成功",greenHouse);
    }

    public Result deleteGreenHouse(GreenHouse greenHouse) {
        greenHouse.setIsDeleted(1);
        if(!greenHouseMapper.updateGreenHouse(greenHouse)){
            return Result.error("删除失败");
        }
        sensorService.deleteByGreenHouseId(greenHouse.getId());
        sensorDataService.deleteByGreenHouseId(greenHouse.getId());
        return Result.success("删除成功");
    }

    public Result updateGreenhouse(GreenHouse greenHouse) {
        if(greenHouseMapper.getGreenHouseById(greenHouse) == null){
            return Result.error("大棚不存在");
        }
        if(!greenHouseMapper.updateGreenHouse(greenHouse)){
            return Result.error("更新失败");
        }
        return Result.success("更新成功");
    }

    public Result getAverageAll(GreenHouse greenHouse) {
        JSONObject json = new JSONObject();
        List<Sensors> sensorsList = new ArrayList<>();
        sensorsList = sensorService.getSensorsByGreenHouse(greenHouse);
        //整合传感器id
        List<Integer> idList = sensorsList.stream().map(Sensors::getId).collect(Collectors.toList());
        List<SensorData> sensorDataList = new ArrayList<>();
        sensorDataList = sensorDataService.getSensorDataByIdList(idList);
        Double data = sensorDataList.stream().mapToDouble(SensorData::getValue).average().orElse(0.0);
        json.put("allAverage",data);
        return Result.success(json);
    }

    public Result getAverageTime(GreenHouse greenHouse) {
        JSONObject json = new JSONObject();
        List<Sensors> sensorsList = new ArrayList<>();
        sensorsList = sensorService.getSensorsByGreenHouse(greenHouse);
        //整合传感器id
        List<Integer> idList = sensorsList.stream().map(Sensors::getId).collect(Collectors.toList());
        List<SensorData> sensorDataList = new ArrayList<>();
        sensorDataList = sensorDataService.getSensorDataByIdList(idList);
        //求每个时间段的平均值
        Integer[] hours = {0, 6, 12,15,18};
        Map<String, Double> result = new HashMap<>();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate today = LocalDate.now();
        for (Integer hour : hours) {
            LocalDateTime startLdt = today.atTime(hour, 0);
            LocalDateTime endLdt = startLdt.plusHours(1);

            Date start = Date.from(startLdt.atZone(zoneId).toInstant());
            Date end = Date.from(endLdt.atZone(zoneId).toInstant());

            List<SensorData> filtered = new ArrayList<>();

            // 过滤数据
            filtered = sensorDataList.stream()
                    .filter(d -> d.getTimestamp() != null && d.getValue() != null)
                    .filter(d -> !d.getTimestamp().before(start) && d.getTimestamp().before(end))
                    .collect(Collectors.toList());
            // 求平均
            Double average = filtered.stream()
                    .mapToDouble(SensorData::getValue)
                    .average()
                    .orElse(0.0);
            // 存入结果
            if(hour == 23){
                hour = 24;
            }
            result.put( hour.toString(), average);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(result);
        return Result.success(jsonObject);
    }

    public Result getAverageOne(GreenHouse greenHouse) {
        Map<String,List<Sensors>> sensorsMap = new HashMap<>();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        List<Sensors> sensorsList = new ArrayList<>();
        sensorsList = sensorService.getSensorsByGreenHouse(greenHouse);
        sensorsMap = sensorsList.stream().collect(Collectors.groupingBy(x -> x.getLocation()));
        //各个采集点的平均数据
        for (String location : sensorsMap.keySet()){
            JSONObject json = new JSONObject();
            List<Sensors> list = sensorsMap.get(location);
            List<Integer> idList = list.stream().map(Sensors::getId).collect(Collectors.toList());
            List<SensorData> sensorDataList = new ArrayList<>();
            sensorDataList = sensorDataService.getTodaySensorDataByIdList(idList);
            Double data = sensorDataList.stream().mapToDouble(x -> x.getValue()).average().orElse(0.0);
            json.put("location",location);
            json.put("data",data);
            jsonObjectList.add(json);
        }
        return Result.success(jsonObjectList);
    }

    public Result getAverageMax(GreenHouse greenHouse) {
        Map<String, List<Sensors>> sensorsMap = new HashMap<>();
        JSONObject json = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        List<Sensors> sensorsList = new ArrayList<>();
        List<SensorData> sensorDataList = new ArrayList<>();
        sensorsList = sensorService.getSensorsByGreenHouse(greenHouse);
        sensorsMap = sensorsList.stream().collect(Collectors.groupingBy(x -> x.getLocation()));
        //各个采集点的平均数据
        for (String location : sensorsMap.keySet()) {
            List<Integer> idList = sensorsMap.get(location).stream().map(Sensors::getId).collect(Collectors.toList());
            List<SensorData> list = new ArrayList<>();
            list = sensorDataService.getTodaySensorDataByIdList(idList);
            sensorDataList.addAll(list);
        }
        Double max = sensorDataList.stream()
                .max(Comparator.comparing(SensorData::getValue))  // 使用 Comparator.comparing 来比较 value
                .map(SensorData::getValue)  // 获取最大值
                .orElse(Double.NEGATIVE_INFINITY);
        Double min = sensorDataList.stream()
                .min(Comparator.comparing(SensorData::getValue))  // 使用 Comparator.comparing 来比较 value
                .map(SensorData::getValue)  // 获取最大值
                .orElse(Double.NEGATIVE_INFINITY);
        json.put("max",max);
        json.put("min",min);
        return Result.success(json);
    }
}
